package com.y.ari.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.y.ari.common.Constants;
import com.y.ari.common.RestResponse;
import com.y.ari.dto.EmpFormDTO;
import com.y.ari.dto.EmployeeDTO;
import com.y.ari.entity.Employee;
import com.y.ari.mapper.EmployeeMapper;
import com.y.ari.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 员工信息 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登录
     *
     * @param empFormDTO
     * @return
     */
    @Override
    public RestResponse login(EmpFormDTO empFormDTO) {
        String password = DigestUtils.md5DigestAsHex(empFormDTO.getPassword().getBytes());

        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        //判断用户是否存在
        queryWrapper.eq(Employee::getUsername, empFormDTO.getUsername())
                .eq(Employee::getPassword, password);
        Employee employee = employeeMapper.selectOne(queryWrapper);
        if (employee == null) {
            return RestResponse.validfail("员工不存在");
        }

        //保存数据到redis
        //生成token
        String token = UUID.randomUUID().toString();
        EmployeeDTO empDTO = new EmployeeDTO();
        BeanUtils.copyProperties(employee, empDTO);

        // 将User对象转为HashMap存储
        Map<String, Object> userMap = BeanUtil.beanToMap(empDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(false));
        String tokenKey = Constants.LOGIN_USER_KEY + token;

        redisTemplate.opsForHash().putAll(tokenKey, userMap);
        //设置有效期token
        redisTemplate.expire(tokenKey, Constants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return RestResponse.success(token, "登录成功");
    }

    @Override
    public RestResponse selEmp() {
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        List<Employee> empList = employeeMapper.selectList(queryWrapper);
        for (Employee emp : empList) {
            emp.setPassword("******");
        }

        if (empList.isEmpty()) {
            RestResponse.validfail("员工为空");
        }

        return RestResponse.success(empList, "");
    }

    @Override
    public RestResponse save(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        String password = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        employee.setPassword(password);

        if (employeeDTO.getId() == null) {
            int insert = employeeMapper.insert(employee);
            if (insert == 0) {
                RestResponse.validfail("添加失败");
            }
            return RestResponse.success("添加成功");
        }
        if (employee.getEmpType().equals("管理人员")) {
            employee.setUsername(null);
            employee.setEmpType("管理人员");
        }
        int i = employeeMapper.updateById(employee);
        if (i == 0) {
            RestResponse.validfail("修改失败");
        }
        return RestResponse.success("修改成功");
    }

    @Override
    public RestResponse delEmp(Long id) {
        int i = employeeMapper.deleteById(id);
        if (i == 0) {
            return RestResponse.validfail("删除失败");
        }
        return RestResponse.success("删除成功");
    }
}
